package com.example.mediarecord;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MediaPlayerActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {
    @BindView(R.id.ture_view)
    public TextureView mTextureView;
    @BindView(R.id.btn_start)
    public Button mButton;

    private boolean isStart = false; //默认false
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_player);
        //初始化ButterKnife
        ButterKnife.bind(this);
    }

    /**
     * 多个点击事件
     */
    @OnClick({R.id.btn_start})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.btn_start:
                if(!isStart){
                    mButton.setText("结束播放");
                    isStart = true;
                    startPlayer();
                }else {
                    mButton.setText("开始播放");
                    isStart = false;
                    stopPlayer();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 开始播放
     */
    private void startPlayer() {
        mediaPlayer = new MediaPlayer();
        //设置准备监听
        mediaPlayer.setOnPreparedListener(this);
        //设置视频播放状态
        mediaPlayer.setOnCompletionListener(this);
        //设置是否循环播放
        mediaPlayer.setLooping(false);
        //指定播放视频的地址
        try {
            mediaPlayer.setDataSource(new File(getExternalFilesDir(""),"a.mp4").getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //设置视频画面
        mediaPlayer.setSurface(new Surface(mTextureView.getSurfaceTexture()));
        mediaPlayer.prepareAsync();
    }

    /**
     * 结束播放
     */
    private void stopPlayer(){
        mediaPlayer.stop();
        mediaPlayer.release();
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        mediaPlayer.start();
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        mButton.setText("开始播放");
        isStart = false;
        stopPlayer();
    }
}